package com.bitcat.firstapp.ui.activity

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.bitcat.firstapp.R
import com.bitcat.firstapp.databinding.ActivityMainBinding
import com.bitcat.firstapp.ui.fragment.NewsFragment
import com.bitcat.firstapp.ui.fragment.ProfileFragment
import com.bitcat.firstapp.ui.fragment.TodoListFragment

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding


    private lateinit var fragmentList: List<Fragment>

    //记录当前显示的fragment
    private var currentFragment:Fragment? = null



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        fragmentList = listOf(
            TodoListFragment(),
            NewsFragment(),
            ProfileFragment()
        )


        binding.bottomNavBar.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.tab_home -> {
                    showFragment(fragmentList[0])
                    true
                }

                R.id.tab_news -> {
                    showFragment(fragmentList[1])
                    true
                }

                R.id.tab_profile -> {
                   showFragment(fragmentList[2])
                    true
                }

                else -> {
                    false
                }
            }

        }

        showFragment(fragmentList[0])

    }


//    fun showFragment(fragment: Fragment) {
//        //方式一：replace方式
//        //1. 获取fragmentManager
//        val fm = supportFragmentManager
//
//        //2. 开启事务
//        val ft = fm.beginTransaction()
//
//        //3. 替换fragment
//        ft.replace(R.id.container, fragment)
//
//        //4. 提交事务
//        ft.commit()
//    }



    fun showFragment(fragment: Fragment) {
        //1. 获取fragmentManager
       val fm = supportFragmentManager

        //2. 开启事务
        val ft = fm.beginTransaction()

        //3.判断是否添加过
        if (!fragment.isAdded){
            ft.add(R.id.container,fragment)
        }

        //4.隐藏当前fragment(缓存起来)
        currentFragment?.let { ft.hide(it) }

        //5.显示目标fragment
        ft.show(fragment)
        currentFragment = fragment


        //提交事务
        ft.commit()
    }
}